<template>
  <el-scrollbar class="h-full">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formState"
      :rules="rules"
      class="mb-6"
      label-position="top"
      require-asterisk-position="right"
    >
      <QuoteCard header="注册方式" description="用户端支持的用户注册方式">
        <el-form-item>
          <!-- <template #label>
            <div class="flex items-center">
              <span class="mr-2 text-[#161a23]">用户注册方式</span>
              <span class="text-danger">*</span>
            </div>
            <div class="text-info text-xs mt-1">用户端支持的用户注册方式</div>
          </template> -->
          <el-radio-group
            v-model="type"
            class="flex flex-col items-start gap-y-4"
          >
            <el-radio class="font-normal" :label="1">仅用户名</el-radio>
            <el-radio class="font-normal" :label="3">仅邮箱注册</el-radio>
            <el-radio class="font-normal" :label="2">用户名或邮箱注册</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="type > 1" class="pl-6">
          <div class="flex mb-4 flex-col w-full bg-[#f7f8fa] rounded p-4">
            <small class="mb-4 text-xs text-info">
              用户端邮箱注册、找回密码等功能使用
            </small>
            <el-form-item
              prop="host"
              class="w-[400px]"
              required
              label="主机地址"
            >
              <el-input
                v-model="formState.host"
                placeholder="请输入邮箱地址"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="w-[400px]"
              prop="port"
              required
              label="主机端口"
            >
              <el-input
                v-model="formState.port"
                placeholder="请输入主机端口"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="w-[400px]"
              prop="title"
              required
              label="邮箱标题"
            >
              <el-input
                v-model="formState.title"
                placeholder="请输入邮箱标题"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="w-[400px]"
              prop="user"
              required
              label="发送方用户名"
            >
              <el-input
                v-model="formState.user"
                placeholder="请输入发送方用户名"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="w-[400px]"
              prop="pwd"
              required
              label="发送方用户密码"
            >
              <basic-password-input
                v-model.trim="formState.pwd"
                placeholder="请输入发送方用户密码"
              />
            </el-form-item>
          </div>

          <div class="flex flex-col w-full bg-[#f7f8fa] rounded p-4">
            <el-form-item prop="email_addr" class="w-[400px]" label="邮箱测试">
              <div class="flex items-center gap-x-4 w-full">
                <el-input
                  v-model="formState.email_addr"
                  maxlength="200"
                  placeholder="请输入邮箱地址"
                ></el-input>
                <el-button
                  :disabled="emailVerifying || wait"
                  class="send-btn"
                  plain
                  @click="handleVerifyEmail"
                  >{{ emailBtnMsg }}</el-button
                >
              </div>
            </el-form-item>
          </div>
        </div>
        <div class="-ml-2">
          <el-divider></el-divider>
          <el-button type="primary" @click="handleSave">保存配置</el-button>
        </div>
      </QuoteCard>
    </el-form>
  </el-scrollbar>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { omit } from 'lodash-es'

import { useVerifyCode } from '@/hooks/useVerifyCode.js'
import ToastUtils from '@/utils/toast'

const loading = ref(false)

const formRef = ref<FormInstance>()
const type = ref(1)
const formState = reactive({
  host: '',
  port: 0,
  pwd: '',
  title: '',
  user: '',
  email_addr: ''
})
const rules: Record<string, FormItemRule[]> = {
  host: [{ required: true, message: '请输入主机地址' }],
  email_addr: [{ type: 'email', message: '请输入正确的邮箱地址' }],
  port: [
    { required: true, message: '请输入主机端口' },
    {
      trigger: 'blur',
      validator(_, value) {
        const item = +value
        const res = /^\d+$/.test(value)
        if (!res || (res && !(item >= 1 && item <= 65535))) {
          return new Error('主机端口范围为1-65535')
        }
        return true
      }
    }
  ],
  title: [{ required: true, message: '请输入邮箱标题' }],
  user: [{ required: true, message: '请输入发送方用户名' }],
  pwd: [{ required: true, message: '请输入发送方用户密码' }]
}

const { time, wait } = useVerifyCode()
const emailStatus = ref(false)
const emailVerifying = ref(false)

const emailBtnMsg = computed(() =>
  emailVerifying.value
    ? '发送中'
    : !wait.value
    ? '发送验证码'
    : `${time.value}秒后重试`
)

onMounted(() => {
  configInfoApi({}).then(res => {
    type.value = res.registration?.register_type as number
    formState.host = res.email?.host as string
    formState.port = res.email?.port as number
    formState.pwd = res.email?.pwd as string
    formState.title = res.email?.title as string
    formState.user = res.email?.user as string
  })
})

const handleSave = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    await editConfigApi({
      registration: {
        register_type: type.value
      },
      email: type.value === 1 ? void 0 : omit(formState, ['email_addr'])
    })
    ToastUtils.success('修改成功')
  } finally {
    loading.value = false
  }
}

const handleVerifyEmail = async () => {
  if (!formState.email_addr) {
    ToastUtils.error('请先输入测试邮箱')
    return
  }
  await formRef.value?.validate()
  emailVerifying.value = true
  try {
    await emailTestApi({
      email: omit(formState, ['email_addr']),
      email_addr: formState.email_addr
    })
    emailStatus.value = true
    wait.value = true
  } catch (error) {
    emailStatus.value = false
  } finally {
    emailVerifying.value = false
  }
}
</script>

<style lang="scss" scoped>
.el-radio {
  height: 20px;
}
</style>
